package com.liaohuakai.piggybank.view

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.liaohuakai.piggybank.base.BaseActivity
import com.liaohuakai.piggybank.databinding.ActivityLoginBinding
import com.liaohuakai.piggybank.viewModel.LoginViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class LoginActivity : BaseActivity() {

    private val binding by lazy {
        ActivityLoginBinding.inflate(layoutInflater)
    }

    private val viewMode by lazy {
        ViewModelProvider(this).get(LoginViewModel::class.java)
    }

    companion object {
        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, LoginActivity::class.java)
            context.startActivity(starter)
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        viewMode.isLoading.observe(this) {
            it?.let {
                if (it) {
                    showLoading()
                } else {
                    hideLoading()
                }
            }
        }

        viewMode.userData.observe(this) {
            Log.e("Leo", "Login Success, user name= ${it.name}, token= ${it.token}")
        }

        binding.activityLoginBtnLogin.setOnClickListener {
            val name = binding.activityLoginEdtUsername.text.toString()
            val pw = binding.activityLoginEdtPw.text.toString()
            if (name.isNotBlank() && pw.isNotBlank()) {
                lifecycleScope.launch{
                    viewMode.login(name, pw)
                }
            }
        }
    }
}